/**
 * Created by ruiyuan on 15-9-12.
 */

require('../../config/globalParameters');
var fs = require('fs');
var crypto = require('crypto');
var archiver = require('archiver');
var isOS = require('os');


var hostOS = isOS.platform();
//logger.info("host platform is --->" + hostOS);
if (hostOS == "win32") {
    var path = __dirname.replace('server\\common\\initialization', 'public/'); //this is window
}
else {
    var path = __dirname.replace('server/common/initialization', 'public/'); //this is linux
}
var home = path + 'market';
var versionPath = '/mnt/market/version/';
var zipPath = '/mnt/market/zip/';

function scan(path, version) {

    var json = {};
    var walk = function (path, json) {
        var files = fs.readdirSync(path);
        files.forEach(function (item) {
            var tmpPath = path + '/' + item;
            var stats = fs.statSync(tmpPath);
            if (stats.isDirectory()) {
                walk(tmpPath, json);
            } else {
                json[tmpPath.replace(home + '/', '')] = getMd5(tmpPath);
            }
        })
    };
    walk(path, json);

    var verZip = archiver('zip');
    verZip.pipe(fs.createWriteStream(zipPath + 'v0_' + version + '.zip'));
    verZip.append(JSON.stringify({version: version}), {name: 'market/config.json'});
    verZip.directory(home, 'market');
    verZip.finalize();

    var vList = fs.readdirSync(versionPath);
    vList.forEach(function (item) {
        if (item.split('.')[0] !== version && item.split('.')[1] === 'json') {
            var changeList = [];
            var v = fs.readFileSync(versionPath + '/' + item);

            for (var key in json) {
                if (json[key] !== JSON.parse(v)[key])changeList.push(key);
            }
            console.log(changeList);

            var zipName = item.split('.')[0] + '_' + version + '.zip';
            var output = fs.createWriteStream(zipPath + zipName);
            var zipArchiver = archiver('zip');
            zipArchiver.pipe(output);
            for (var i = 0; i < changeList.length; i++) {
                zipArchiver.append(fs.createReadStream(home + '/' + changeList[i]), {'name': 'market/' + changeList[i]});
            }
            zipArchiver.append(JSON.stringify({version: version}), {name: 'market/config.json'});
            //zipArchiver.append(JSON.stringify(json), {name: 'verify.json'});
            zipArchiver.finalize();
        }
    });

    fs.writeFileSync(versionPath + version + '.json', JSON.stringify(json), 'utf-8');
    console.log('market --- generate --- success')
}

function getMd5(p) {
    var str = fs.readFileSync(p, 'utf-8');
    var md5um = crypto.createHash('md5');
    md5um.update(str);
    return md5um.digest('hex');
}

scan(home, MARKET_VERSION);
